<template>
  <div class="liquidation-monitor">
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon">💰</div>
        <div class="stat-title">总爆仓金额 ({{ formatTimeWindowLabel(liquidationStore.selectedTimeWindow) }})</div>
        <div class="stat-value">{{ formatAmount(liquidationStore.totalLiquidation.total_amount) }}</div>
        <div class="stat-change">
          <span class="long-stat">📈 多头: {{ formatAmount(liquidationStore.totalLiquidation.long_amount) }}</span>
          <span class="short-stat">📉 空头: {{ formatAmount(liquidationStore.totalLiquidation.short_amount) }}</span>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">📊</div>
        <div class="stat-title">总爆仓量</div>
        <div class="stat-value">{{ formatVolume(liquidationStore.totalLiquidation.total_volume) }}</div>
        <div class="stat-change">
          <span class="long-stat">📈 多头: {{ formatVolume(liquidationStore.totalLiquidation.long_volume) }}</span>
          <span class="short-stat">📉 空头: {{ formatVolume(liquidationStore.totalLiquidation.short_volume) }}</span>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">🔢</div>
        <div class="stat-title">爆仓笔数</div>
        <div class="stat-value">{{ formatNumber(liquidationStore.totalLiquidation.total_count, 0) }}</div>
        <div class="stat-change">
          <span class="long-stat">📈 多头: {{ formatNumber(liquidationStore.totalLiquidation.long_count, 0) }}</span>
          <span class="short-stat">📉 空头: {{ formatNumber(liquidationStore.totalLiquidation.short_count, 0) }}</span>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">🎯</div>
        <div class="stat-title">监控币种</div>
        <div class="stat-value">{{ liquidationStore.coins.length }}</div>
        <div class="stat-change">
          <span class="status-indicator">🟢 实时更新中</span>
        </div>
      </div>
    </div>
    
    <!-- BTC和ETH专用卡片 -->
    <div class="featured-coins">
      <div class="featured-coin-card btc-card">
        <div class="coin-header">
          <img 
            src="https://assets.coincap.io/assets/icons/btc@2x.png" 
            alt="BTC"
            class="featured-coin-logo"
            @error="handleImageError"
          />
          <div class="coin-info">
            <h3>BTC</h3>
            <span class="coin-label">比特币</span>
          </div>
          <div class="expand-toggle" @click.stop="toggleBTCRecords" title="切换展开/收起">
            <el-icon class="expand-icon">
              <component :is="showBTCRecords ? ArrowUp : ArrowDown" />
            </el-icon>
          </div>
        </div>
        
        <!-- 横向净爆仓数据 -->
        <div class="coin-stats-horizontal">
          <div class="stat-item-horizontal">
            <div class="stat-icon">📈</div>
            <span class="stat-label">1m净爆仓</span>
            <span class="stat-value btc-amount">{{ getBTCNetLiquidation('1m') }}</span>
          </div>
          <div class="stat-item-horizontal">
            <div class="stat-icon">📊</div>
            <span class="stat-label">3m净爆仓</span>
            <span class="stat-value btc-amount">{{ getBTCNetLiquidation('3m') }}</span>
          </div>
          <div class="stat-item-horizontal">
            <div class="stat-icon">📉</div>
            <span class="stat-label">5m净爆仓</span>
            <span class="stat-value btc-amount">{{ getBTCNetLiquidation('5m') }}</span>
          </div>
          <div class="stat-item-horizontal">
            <div class="stat-icon">⚡</div>
            <span class="stat-label">10m净爆仓</span>
            <span class="stat-value btc-amount">{{ getBTCNetLiquidation('10m') }}</span>
          </div>
          <div class="stat-item-horizontal">
            <div class="stat-icon">🔥</div>
            <span class="stat-label">15m净爆仓</span>
            <span class="stat-value btc-amount">{{ getBTCNetLiquidation('15m') }}</span>
          </div>
          <div class="stat-item-horizontal">
            <div class="stat-icon">💎</div>
            <span class="stat-label">30m净爆仓</span>
            <span class="stat-value btc-amount">{{ getBTCNetLiquidation('30m') }}</span>
          </div>
        </div>
        
        <!-- BTC爆仓记录表格 -->
        <div v-show="showBTCRecords" class="coin-records">
          <div class="record-controls">
            <el-select v-model="btcFilter" placeholder="筛选条件" size="small" style="width: 120px;">
              <el-option label="全部" value="all" />
              <el-option label="≥1千$" value="1000" />
              <el-option label="≥1万$" value="10000" />
              <el-option label="≥10万$" value="100000" />
              <el-option label="≥100万$" value="1000000" />
            </el-select>
          </div>
          <el-table
            :data="filteredBTCRecords"
            size="small"
            height="250"
            stripe
            :row-class-name="getRecordRowClass"
            style="width: 100%"
            :header-cell-style="{ background: '#e3f2fd', color: '#1976d2', fontWeight: 'bold' }"
          >
            <el-table-column prop="timestamp" label="时间" min-width="100" align="center">
              <template #default="{ row }">
                <span>{{ formatTime(row.timestamp, 'HH:mm:ss') }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="side" label="方向" min-width="70" align="center">
              <template #default="{ row }">
                <el-tag :type="row.side === 'long' ? 'success' : 'danger'" size="small">
                  {{ row.side === 'long' ? '多单' : '空单' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="爆仓金额" min-width="120" align="right">
              <template #default="{ row }">
                <span :class="getAmountClass(row.amount)">{{ formatAmount(row.amount) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" min-width="90" align="right">
              <template #default="{ row }">
                <span>${{ formatNumber(row.price, 2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="exchange" label="交易所" min-width="80" align="center" />
          </el-table>
        </div>
      </div>
      
      <div class="featured-coin-card eth-card">
        <div class="coin-header">
          <img 
            src="https://assets.coincap.io/assets/icons/eth@2x.png" 
            alt="ETH"
            class="featured-coin-logo"
            @error="handleImageError"
          />
          <div class="coin-info">
            <h3>ETH</h3>
            <span class="coin-label">以太坊</span>
          </div>
          <div class="expand-toggle" @click.stop="toggleETHRecords" title="切换展开/收起">
            <el-icon class="expand-icon">
              <component :is="showETHRecords ? ArrowUp : ArrowDown" />
            </el-icon>
          </div>
        </div>
        
        <!-- 横向净爆仓数据 -->
        <div class="coin-stats-horizontal">
          <div class="stat-item-horizontal">
            <div class="stat-icon">📈</div>
            <span class="stat-label">1m净爆仓</span>
            <span class="stat-value eth-amount">{{ getETHNetLiquidation('1m') }}</span>
          </div>
          <div class="stat-item-horizontal">
            <div class="stat-icon">📊</div>
            <span class="stat-label">3m净爆仓</span>
            <span class="stat-value eth-amount">{{ getETHNetLiquidation('3m') }}</span>
          </div>
          <div class="stat-item-horizontal">
            <div class="stat-icon">📉</div>
            <span class="stat-label">5m净爆仓</span>
            <span class="stat-value eth-amount">{{ getETHNetLiquidation('5m') }}</span>
          </div>
          <div class="stat-item-horizontal">
            <div class="stat-icon">⚡</div>
            <span class="stat-label">10m净爆仓</span>
            <span class="stat-value eth-amount">{{ getETHNetLiquidation('10m') }}</span>
          </div>
          <div class="stat-item-horizontal">
            <div class="stat-icon">🔥</div>
            <span class="stat-label">15m净爆仓</span>
            <span class="stat-value eth-amount">{{ getETHNetLiquidation('15m') }}</span>
          </div>
          <div class="stat-item-horizontal">
            <div class="stat-icon">💎</div>
            <span class="stat-label">30m净爆仓</span>
            <span class="stat-value eth-amount">{{ getETHNetLiquidation('30m') }}</span>
          </div>
        </div>
        
        <!-- ETH爆仓记录表格 -->
        <div v-show="showETHRecords" class="coin-records">
          <div class="record-controls">
            <el-select v-model="ethFilter" placeholder="筛选条件" size="small" style="width: 120px;">
              <el-option label="全部" value="all" />
              <el-option label="≥1千$" value="1000" />
              <el-option label="≥1万$" value="10000" />
              <el-option label="≥10万$" value="100000" />
              <el-option label="≥100万$" value="1000000" />
            </el-select>
          </div>
          <el-table
            :data="filteredETHRecords"
            size="small"
            height="250"
            stripe
            :row-class-name="getRecordRowClass"
            style="width: 100%"
            :header-cell-style="{ background: '#e3f2fd', color: '#1976d2', fontWeight: 'bold' }"
          >
            <el-table-column prop="timestamp" label="时间" min-width="100" align="center">
              <template #default="{ row }">
                <span>{{ formatTime(row.timestamp, 'HH:mm:ss') }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="side" label="方向" min-width="70" align="center">
              <template #default="{ row }">
                <el-tag :type="row.side === 'long' ? 'success' : 'danger'" size="small">
                  {{ row.side === 'long' ? '多单' : '空单' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="爆仓金额" min-width="120" align="right">
              <template #default="{ row }">
                <span :class="getAmountClass(row.amount)">{{ formatAmount(row.amount) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" min-width="90" align="right">
              <template #default="{ row }">
                <span>${{ formatNumber(row.price, 2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="exchange" label="交易所" min-width="80" align="center" />
          </el-table>
        </div>
      </div>
    </div>
    

    
    <!-- 数据表格 -->
    <div class="data-table card">
      <div class="table-header">
        <div class="table-title">币种爆仓排行榜</div>
        <div class="table-actions">
          <!-- 关注币种多选 -->
          <el-select
            v-model="selectedCoins"
            multiple
            filterable
            collapse-tags
            placeholder="选择关注币种"
            size="small"
            style="min-width: 220px"
          >
            <el-option
              v-for="opt in coinOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>

          <!-- 10分钟爆仓量筛选 -->
          <el-select v-model="amount10mFilter" size="small" style="width: 160px" placeholder="10分钟爆仓量">
            <el-option label="全部" value="all" />
            <el-option label="> 1万$" value=">1w" />
            <el-option label="> 10万$" value=">10w" />
            <el-option label="> 100万$" value=">100w" />
          </el-select>

          <!-- 搜索框 -->
          <el-input
            v-model="liquidationStore.searchQuery"
            placeholder="搜索币种"
            style="width: 200px"
            clearable
            @input="handleSearch"
            size="small"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <!-- 刷新/自动刷新 -->
          <el-button 
            type="primary" 
            @click="refreshData"
            :loading="liquidationStore.loading"
            :icon="Refresh"
            size="small"
          >
            刷新数据
          </el-button>
          <el-button 
            :type="liquidationStore.autoRefresh ? 'warning' : 'success'"
            @click="toggleAutoRefresh"
            :icon="liquidationStore.autoRefresh ? VideoPause : VideoPlay"
            size="small"
          >
            {{ liquidationStore.autoRefresh ? '停止自动刷新' : '开启自动刷新' }}
          </el-button>

          <el-tag :type="liquidationStore.autoRefresh ? 'success' : 'info'" size="small">
            {{ liquidationStore.autoRefresh ? '自动刷新' : '手动刷新' }}
          </el-tag>
          <el-tag type="info" size="small">{{ formatTimeWindowLabel(liquidationStore.selectedTimeWindow) }}数据</el-tag>
          <el-tag v-if="lastUpdateTime" type="success" size="small">{{ formatRelativeTime(lastUpdateTime) }}更新</el-tag>
        </div>
      </div>
      
<el-table
        :data="displayData"
        :loading="liquidationStore.loading"
        stripe
        border
        height="600"
        row-class-name="table-row-hover"
      >
        <el-table-column type="index" label="排名" min-width="80" align="center" />
        
        <el-table-column prop="coin" label="币种" min-width="140" align="center">
          <template #default="{ row }">
            <div class="coin-display">
              <img 
                :src="`https://assets.coincap.io/assets/icons/${formatCoinName(row.coin).toLowerCase()}@2x.png`" 
                :alt="formatCoinName(row.coin)"
                class="coin-logo"
                @error="handleImageError"
              />
              <span class="coin-name">{{ formatCoinName(row.coin) }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="1m" min-width="130" align="right">
          <template #header>
            <span class="sortable-header" @click="handleSort('1m')">
              1m净爆仓 {{ getSortIcon('1m') }}
            </span>
          </template>
          <template #default="{ row }">
            <span :class="getNetLiquidationClass(row, '1m')">
              {{ formatNetLiquidationAmount(row, '1m') }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="3m" min-width="130" align="right">
          <template #header>
            <span class="sortable-header" @click="handleSort('3m')">
              3m净爆仓 {{ getSortIcon('3m') }}
            </span>
          </template>
          <template #default="{ row }">
            <span :class="getNetLiquidationClass(row, '3m')">
              {{ formatNetLiquidationAmount(row, '3m') }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="5m" min-width="130" align="right">
          <template #header>
            <span class="sortable-header" @click="handleSort('5m')">
              5m净爆仓 {{ getSortIcon('5m') }}
            </span>
          </template>
          <template #default="{ row }">
            <span :class="getNetLiquidationClass(row, '5m')">
              {{ formatNetLiquidationAmount(row, '5m') }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="10m" min-width="130" align="right">
          <template #header>
            <span class="sortable-header" @click="handleSort('10m')">
              10m净爆仓 {{ getSortIcon('10m') }}
            </span>
          </template>
          <template #default="{ row }">
            <span :class="getNetLiquidationClass(row, '10m')">
              {{ formatNetLiquidationAmount(row, '10m') }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="15m" min-width="130" align="right">
          <template #header>
            <span class="sortable-header" @click="handleSort('15m')">
              15m净爆仓 {{ getSortIcon('15m') }}
            </span>
          </template>
          <template #default="{ row }">
            <span :class="getNetLiquidationClass(row, '15m')">
              {{ formatNetLiquidationAmount(row, '15m') }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="30m" min-width="130" align="right">
          <template #header>
            <span class="sortable-header" @click="handleSort('30m')">
              30m净爆仓 {{ getSortIcon('30m') }}
            </span>
          </template>
          <template #default="{ row }">
            <span :class="getNetLiquidationClass(row, '30m')">
              {{ formatNetLiquidationAmount(row, '30m') }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="lastUpdate" label="最后更新" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="small">
              {{ formatRelativeTime(row.lastUpdate) }}
            </el-tag>
          </template>
        </el-table-column>
        
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { 
  Search, 
  Refresh, 
  VideoPlay, 
  VideoPause, 
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useLiquidationStore } from '@/stores/liquidation'
import api from '@/api'
import { 
  formatAmount, 
  formatVolume, 
  formatNumber, 
  formatTime, 
  formatRelativeTime, 
  formatCoinName, 
  formatTimeWindowLabel,
  formatNetAmount,
  calculateNetLiquidation,
  debounce 
} from '@/utils/format'

const liquidationStore = useLiquidationStore()

const lastUpdateTime = ref(null)

// 关注筛选相关
const selectedCoins = ref([])
const amount10mFilter = ref('all')

// 排序相关状态
const sortColumn = ref('1m')
const sortOrder = ref('desc') // 'asc' 或 'desc'

// 爆仓记录相关状态
const showBTCRecords = ref(false)
const showETHRecords = ref(false)
const btcFilter = ref('1000')
const ethFilter = ref('1000')
const btcRecords = ref([])
const ethRecords = ref([])

// 计算属性
// 原始表格源（排序，不做筛选）
const tableSource = computed(() => {
  const sortedCoins = [...liquidationStore.filteredCoins].sort((a, b) => {
    const aData = a.timeWindows[sortColumn.value]
    const bData = b.timeWindows[sortColumn.value]
    if (!aData && !bData) return 0
    if (!aData) return 1
    if (!bData) return -1
    const aLong = aData.long?.amount || 0
    const aShort = aData.short?.amount || 0
    const bLong = bData.long?.amount || 0
    const bShort = bData.short?.amount || 0
    const aNet = Math.abs(aLong - aShort)
    const bNet = Math.abs(bLong - bShort)
    const result = bNet - aNet
    return sortOrder.value === 'desc' ? result : -result
  })
  return sortedCoins
})

// 关注币种选项（基于当前表格源动态生成）
const coinOptions = computed(() => {
  return tableSource.value.map(c => ({ label: c.coin.toUpperCase(), value: c.coin }))
})

// 10分钟爆仓金额阈值
const amount10mThreshold = computed(() => {
  switch (amount10mFilter.value) {
    case '>1w':
      return 10_000
    case '>10w':
      return 100_000
    case '>100w':
      return 1_000_000
    default:
      return 0
  }
})

// 应用多选币种 + 10m阈值后的表格数据
const displayData = computed(() => {
  let list = tableSource.value

  // 多选关注币种过滤
  if (selectedCoins.value && selectedCoins.value.length > 0) {
    const set = new Set(selectedCoins.value.map(v => v.toUpperCase()))
    list = list.filter(item => set.has(item.coin.toUpperCase()))
  }

  // 10分钟总爆仓额阈值过滤
  const th = amount10mThreshold.value
  if (th > 0) {
    list = list.filter(item => (item.timeWindows?.['10m']?.total?.amount || 0) >= th)
  }

  return list.slice(0, 100)
})

// 防抖搜索
const handleSearch = debounce(() => {
  // 搜索逻辑已在store的computed中处理
}, 300)

// 表头点击排序
const handleSort = (column) => {
  if (sortColumn.value === column) {
    // 如果点击的是当前排序列，切换排序顺序
    sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc'
  } else {
    // 如果点击的是新列，设置为该列并默认降序
    sortColumn.value = column
    sortOrder.value = 'desc'
  }
}

// 获取排序图标
const getSortIcon = (column) => {
  if (sortColumn.value !== column) return ''
  return sortOrder.value === 'desc' ? '↓' : '↑'
}

// 方法
const refreshData = async () => {
  try {
    await liquidationStore.getAllCoins(100)
    lastUpdateTime.value = Date.now()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  }
}

const handleTimeWindowChange = (window) => {
  liquidationStore.setTimeWindow(window)
  refreshData()
}

const toggleAutoRefresh = () => {
  liquidationStore.toggleAutoRefresh()
  if (liquidationStore.autoRefresh) {
    ElMessage.success('已开启自动刷新')
    liquidationStore.startAutoRefresh(1000) // 每秒刷新一次
  } else {
    ElMessage.info('已停止自动刷新')
  }
}


// 格式化净爆仓金额
const formatNetLiquidationAmount = (row, timeWindow) => {
  const windowData = row.timeWindows[timeWindow]
  if (!windowData) return '0万$'
  
  const longAmount = windowData.long?.amount || 0
  const shortAmount = windowData.short?.amount || 0
  const netLiquidation = calculateNetLiquidation(longAmount, shortAmount)
  
  return formatNetAmount(Math.abs(netLiquidation.amount))
}

// 获取净爆仓样式类
const getNetLiquidationClass = (row, timeWindow) => {
  const windowData = row.timeWindows[timeWindow]
  if (!windowData) return 'text-info'
  
  const longAmount = windowData.long?.amount || 0
  const shortAmount = windowData.short?.amount || 0
  const netLiquidation = calculateNetLiquidation(longAmount, shortAmount)
  
  if (netLiquidation.isLong) {
    return 'text-success' // 绿色 - 净多单爆仓
  } else if (netLiquidation.isShort) {
    return 'text-danger'  // 红色 - 净空单爆仓
  } else {
    return 'text-info'    // 灰色 - 平衡
  }
}

// 处理图片加载错误
const handleImageError = (event) => {
  // 图片加载失败时隐藏图片
  event.target.style.display = 'none'
}

// 获取BTC净爆仓数据
const getBTCNetLiquidation = (timeWindow) => {
  const btcData = liquidationStore.filteredCoins.find(coin => coin.coin === 'BTC')
  if (!btcData) return '0万$'
  return formatNetLiquidationAmount(btcData, timeWindow)
}

// 获取ETH净爆仓数据
const getETHNetLiquidation = (timeWindow) => {
  const ethData = liquidationStore.filteredCoins.find(coin => coin.coin === 'ETH')
  if (!ethData) return '0万$'
  return formatNetLiquidationAmount(ethData, timeWindow)
}

// 爆仓记录相关方法
const toggleBTCRecords = () => {
  showBTCRecords.value = !showBTCRecords.value
}

const toggleETHRecords = () => {
  showETHRecords.value = !showETHRecords.value
}

// 获取筛选后的BTC记录
const fetchFilteredBTCRecords = async () => {
  try {
    const minAmount = btcFilter.value === 'all' ? 0 : parseFloat(btcFilter.value)
    const response = await api.getLiquidationRecords('BTC', 100, minAmount)
    if (response.data && response.data.records) {
      btcRecords.value = response.data.records.map(record => ({
        timestamp: record.timestamp,
        side: record.side,
        amount: record.amount,
        price: record.price,
        exchange: record.exchange
      }))
    }
  } catch (error) {
    console.error('获取BTC爆仓记录失败:', error)
    btcRecords.value = []
  }
}

// 获取筛选后的ETH记录
const fetchFilteredETHRecords = async () => {
  try {
    const minAmount = ethFilter.value === 'all' ? 0 : parseFloat(ethFilter.value)
    const response = await api.getLiquidationRecords('ETH', 100, minAmount)
    if (response.data && response.data.records) {
      ethRecords.value = response.data.records.map(record => ({
        timestamp: record.timestamp,
        side: record.side,
        amount: record.amount,
        price: record.price,
        exchange: record.exchange
      }))
    }
  } catch (error) {
    console.error('获取ETH爆仓记录失败:', error)
    ethRecords.value = []
  }
}

// 筛选后的BTC记录（直接返回，因为已经在API层面筛选）
const filteredBTCRecords = computed(() => {
  return btcRecords.value
})

// 筛选后的ETH记录（直接返回，因为已经在API层面筛选）
const filteredETHRecords = computed(() => {
  return ethRecords.value
})

// 获取记录行样式类
const getRecordRowClass = ({ row }) => {
  if (row.amount >= 1000000) {
    return 'high-amount-row'
  }
  return ''
}

// 获取金额样式类
const getAmountClass = (amount) => {
  if (amount >= 1000000) {
    return 'high-amount-text'
  }
  return ''
}

// 获取爆仓记录数据
const fetchLiquidationRecords = async () => {
  try {
    // 获取BTC爆仓记录
    const btcResponse = await api.getLiquidationRecords('BTC', 100, 0)
    if (btcResponse.data && btcResponse.data.records) {
      btcRecords.value = btcResponse.data.records.map(record => ({
        timestamp: record.timestamp,
        side: record.side,
        amount: record.amount,
        price: record.price,
        exchange: record.exchange
      }))
    }
    
    // 获取ETH爆仓记录
    const ethResponse = await api.getLiquidationRecords('ETH', 100, 0)
    if (ethResponse.data && ethResponse.data.records) {
      ethRecords.value = ethResponse.data.records.map(record => ({
        timestamp: record.timestamp,
        side: record.side,
        amount: record.amount,
        price: record.price,
        exchange: record.exchange
      }))
    }
  } catch (error) {
    console.error('获取爆仓记录失败:', error)
    // 如果API调用失败，使用空数组
    btcRecords.value = []
    ethRecords.value = []
  }
}

// 监听筛选条件变化
watch(btcFilter, () => {
  fetchFilteredBTCRecords()
})

watch(ethFilter, () => {
  fetchFilteredETHRecords()
})

// 生命周期
onMounted(async () => {
  try {
    await refreshData()
    await fetchLiquidationRecords()
    
    // 开启自动刷新 - 每秒刷新
    if (liquidationStore.autoRefresh) {
      liquidationStore.startAutoRefresh(1000)
    }
    
    // 设置爆仓记录每秒刷新
    setInterval(() => {
      // 根据当前筛选条件刷新记录
      fetchFilteredBTCRecords()
      fetchFilteredETHRecords()
    }, 1000)
  } catch (error) {
    console.error('初始化失败:', error)
  }
})

onUnmounted(() => {
  liquidationStore.stopAutoRefresh()
})
</script>

<style lang="scss" scoped>
.liquidation-monitor {
  .control-panel {
    margin-bottom: 20px;
    
    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h2 {
        margin: 0;
        color: #303133;
        font-size: 24px;
        font-weight: 600;
      }
    }
    
    .panel-controls {
      display: flex;
      gap: 24px;
      align-items: center;
      flex-wrap: wrap;
      
      .control-group {
        display: flex;
        align-items: center;
        gap: 8px;
        
        label {
          font-weight: 500;
          color: #606266;
          white-space: nowrap;
        }
      }
    }
  }
  
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
    gap: 16px;
    margin-bottom: 16px;
    align-items: stretch;
  }
  
  .data-table {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
      border-bottom: 1px solid #e9ecef;
      margin-bottom: 0;

      .table-title {
        font-size: 18px;
        font-weight: 700;
        color: #2c3e50;
      }

      .table-actions {
        display: flex;
        gap: 10px;
        align-items: center;
        flex-wrap: wrap;
      }
    }
    
    // 表格表头样式优化
    :deep(.el-table__header-wrapper) {
      .el-table__header {
        th {
          background: #e3f2fd !important;
          color: #1976d2 !important;
          font-weight: 600 !important;
          border-bottom: 2px solid #dee2e6 !important;
        }
      }
    }
    
    .sortable-header {
      cursor: pointer;
      user-select: none;
      transition: color 0.2s ease;
      
      &:hover {
        color: #0d47a1 !important;
      }
    }
    
    // 表格行样式
    :deep(.el-table__body-wrapper) {
      .el-table__row {
        &:hover {
          background-color: #f8f9fa !important;
        }
      }
    }
    
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 24px;
      background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
      border-bottom: 1px solid #e9ecef;
      margin-bottom: 0;
      
      .table-title {
        font-size: 20px;
        font-weight: 700;
        color: #2c3e50;
        display: flex;
        align-items: center;
        gap: 8px;
        
        &::before {
          content: '📊';
          font-size: 18px;
        }
      }
      
      .table-info {
        display: flex;
        gap: 12px;
        align-items: center;
      }
    }
  }
}

:deep(.table-row-hover) {
  cursor: pointer;
  transition: all 0.2s ease;
  
  &:hover {
    background-color: #f5f7fa !important;
  }
}

.coin-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  
  .coin-logo {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    object-fit: cover;
    flex-shrink: 0;
  }
  
  .coin-name {
    font-weight: 600;
    color: #303133;
    font-size: 14px;
  }
}

// BTC和ETH专用卡片样式
.featured-coins {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  margin: 20px 0;
}

.featured-coin-card {
  background: #ffffff !important;
  border-radius: 12px;
  padding: 12px;
  color: #1f2937;
  box-shadow: var(--shadow-soft);
  border: 1px solid var(--color-border);
  transition: box-shadow 0.2s ease, transform 0.2s ease;
  position: relative;
  
  &:hover {
    /* 取消悬停动画效果 */
    transform: none;
    box-shadow: var(--shadow-soft);
  }
  
  &.btc-card {
    border-left: 4px solid var(--color-warning);
  }
  
  &.eth-card {
    border-left: 4px solid var(--color-primary);
  }
  
  .expand-toggle {
    position: absolute;
    top: 8px;
    right: 8px;
  }
  
  .expand-icon {
    font-size: 16px;
    color: var(--color-muted);
    opacity: 0.9;
    cursor: pointer;
    transition: transform 0.2s ease, opacity 0.2s ease;
  }
  .expand-icon:hover {
    transform: scale(1.15);
    opacity: 1;
  }
}

.coin-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  
  .featured-coin-logo {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    object-fit: cover;
  }
  
.coin-info {
    display: flex;
    align-items: baseline;
    gap: 6px;

    h3 {
      margin: 0;
      font-size: 18px;
      line-height: 1;
      font-weight: 700;
      letter-spacing: -0.2px;
      display: inline-block;
      color: #111827;
    }
    
    .coin-label {
      display: inline-block;
      font-size: 12px;
      opacity: 1;
      font-weight: 500;
      line-height: 1;
      color: var(--color-muted);
    }
  }
}

.coin-stats {
  display: flex;
  flex-direction: column;
  gap: 16px;
  
  .stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .stat-label {
      font-size: 14px;
      opacity: 0.9;
      font-weight: 500;
    }
    
    .stat-value {
      font-size: 18px;
      font-weight: 700;
      text-align: right;
      
      &.btc-amount, &.eth-amount {
        color: #000;
        text-shadow: none;
      }
      
      &.btc-volume, &.eth-volume {
        color: rgba(255, 255, 255, 0.95);
        font-size: 16px;
      }
    }
  }
}

:deep(.el-table) {
  border-radius: 0;
  border: none;
  width: 100% !important;
  
  .el-table__header {
    width: 100% !important;
    
    th {
      background: #e3f2fd !important;
      color: #1976d2 !important;
      font-weight: 700;
      font-size: 14px;
      border-bottom: none;
      padding: 16px 12px;
      text-align: center;
      
      .cell {
        color: #1976d2 !important;
        font-weight: 700;
      }
    }
  }
  
  .el-table__body {
    width: 100% !important;
    
    tr {
      transition: all 0.2s ease;
      
      &:nth-child(even) {
        background-color: #f8f9fa;
      }
      
      &:hover {
        background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%) !important;
        transform: scale(1.01);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      td {
        padding: 14px 12px;
        border-bottom: 1px solid #e9ecef;
        
        .cell {
          font-weight: 500;
        }
      }
    }
  }
  
  .el-table__empty-block {
    background: white;
  }
}



.high-amount-text {
  color: #dc3545 !important;
  font-weight: 700 !important;
}

.coin-stats-horizontal {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 8px;
  margin: 8px 0 4px;
  
.stat-item-horizontal {
    background: #ffffff;
    border: 1px solid var(--color-border);
    border-radius: 10px;
    padding: 10px 6px;
    text-align: center;
    transition: all 0.2s ease;
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
      transition: left 0.4s ease;
    }
    
    &:hover {
      background: rgba(255, 255, 255, 0.18);
      transform: translateY(-1px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
      
      &::before {
        left: 100%;
      }
    }
    
    .stat-icon {
      font-size: 13px;
      margin-bottom: 2px;
      display: block;
      opacity: 0.9;
    }
    
.stat-label {
      display: block;
      font-size: 12px;
      color: var(--color-muted);
      margin-bottom: 4px;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.4px;
    }
    
.stat-value {
      display: block;
      font-size: 13px;
      font-weight: 700;
      color: #111827;
      text-shadow: none;
      
      &.btc-amount {
        color: #000;
      }
      
      &.eth-amount {
        color: #000;
      }
    }
  }
}

.stat-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border: 1px solid #eef2f6;
  transition: box-shadow 0.2s ease, transform 0.2s ease;
  display: grid;
  grid-template-columns: 32px 1fr;
  grid-auto-rows: min-content;
  grid-column-gap: 12px;
  align-items: start;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }

  .stat-icon {
    font-size: 18px;
    line-height: 1;
    grid-column: 1;
    grid-row: 1 / span 3;
  }

  .stat-title {
    grid-column: 2;
    font-size: 14px;
    color: #4b5563;
    margin: 0 0 6px 0;
    font-weight: 700;
    letter-spacing: 0.2px;
    line-height: 1.2;
  }

  .stat-value {
    grid-column: 2;
    font-size: 26px;
    font-weight: 800;
    color: #1f2937;
    margin: 0 0 4px 0;
    line-height: 1.15;
    word-break: break-word;
  }

  .stat-change {
    grid-column: 2;
    font-size: 11px;
    color: #6b7280;
    font-weight: 500;
    line-height: 1.25;
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .liquidation-monitor {
    .panel-controls {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;
      
      .control-group {
        justify-content: space-between;
      }
    }
    
    .stats-grid {
      grid-template-columns: 1fr;
    }
    
    .featured-coins {
      grid-template-columns: 1fr;
    }
    
    .coin-stats-horizontal {
      flex-wrap: wrap;
      gap: 6px;
      
      .stat-item-horizontal {
        flex: 1 1 calc(50% - 3px);
        min-width: 120px;
        padding: 8px 6px;
        
        .stat-label {
          font-size: 12px;
        }
        
        .stat-value {
          font-size: 14px;
        }
      }
    }
  }
}
// 筛选器样式优化
.record-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 8px;
  border: 1px solid #e9ecef;
  margin-bottom: 16px;
  
  :deep(.el-select) {
    .el-select__wrapper {
      background: white;
      border: 1px solid #d0d7de;
      border-radius: 6px;
      transition: all 0.2s ease;
      
      &:hover {
        border-color: #4a90e2;
      }
      
      &.is-focused {
        border-color: #4a90e2;
        box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.1);
      }
    }
  }
  
  :deep(.el-input) {
    .el-input__wrapper {
      background: white;
      border: 1px solid #d0d7de;
      border-radius: 6px;
      transition: all 0.2s ease;
      
      &:hover {
        border-color: #4a90e2;
      }
      
      &.is-focus {
        border-color: #4a90e2;
        box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.1);
      }
    }
  }
}
</style>